<?php

/**
 * Users Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  MIAOCMS
 * @version  1.0
 */
class UsersController extends AppController {

    /**
     * Controller name
     *
     * @var string
     * @access public
     */
    var $name = 'Users';
    var $components = array(
    	'Auth' => array(
            'authenticate' => array(
                'Form'=>array(
                        'userModel' => 'User',
                		'recursive' => 1,
                        'fields'=>array(
                                'username'=>'email',
                                'password'=>'password'
                        )
                ),
            ),
//          'authorize' => 'Controller',
        ),
    	'Acl',
        'Email',
    	'Kcaptcha',
    	'Cookie' => array('name' => 'MIAOCMS', 'time' => '+2 weeks'),
    );
    
    public $layout = 'user_default';
    /**
     * Models used by the Controller
     *
     * @var array
     * @access public
     */
    var $uses = array('User', 'Oauthbind');
    
    public function beforeFilter(){
    	parent::beforeFilter();
    	if( defined('UC_APPID') ) {
    		if(UC_REMOTEUSER == true){
    			$this->Auth->authenticate = array('UCenter');
    		}
    		else{
    			$this->Hook->loadhook('UCenterHook');
    		}
    	}
    	
    	$host = $_SERVER['HTTP_HOST'];
    	$host_arr = explode('.',$host);
    	if(count($host_arr) > 2) {
    	    array_shift($host_arr);
    	    $this->Cookie->domain = implode('.',$host_arr);
    	}
    	
    	if( in_array($this->action,array('checkQrLogin','keep_session','score','lists')) ){
    	    session_write_close(); // 对于不会出现session赋值的操作，直接结束session锁的占用，
    	}
    	
    	$this->Auth->allowedActions = array('register','login','logout','getLoginQr','checkQrLogin','send_msg','info','avatars','invite','forgot','checkemail','captcha','reset','resetByMobile','check','keep_session');
    }
    
    public function board(){
        
    }

    function captcha() {
        error_reporting(0);
        if (1) {
            //Kcaptcha
            $this->Kcaptcha->render_captcha();
            exit;
        }
// 		else
// 		{ 
// 			//Securimage
// 			$this->autoRender = false;  
// 	        //override variables set in the component - look in component for full list 
// //	        $this->captcha->image_height = 75; 
// //	        $this->captcha->image_width = 350; 
// //	        $this->captcha->image_bg_color = '#ffffff'; 
// //	        $this->captcha->line_color = '#cccccc'; 
// //	        $this->captcha->arc_line_colors = '#999999,#cccccc'; 
// //	        $this->captcha->code_length = 5; 
// //	        $this->captcha->font_size = 45; 
// 	        $this->captcha->text_color = '#000000'; 
// 	        $this->captcha->show(); //dynamically creates an image 
// 		}
    }

    public function account() {
        $this->pageTitle = __('Users', true);
    }

    function index() {
        $this->pageTitle = __('Users', true);
        
        //$this->layout = 'user_portlet';
    }

    function layout() {
        $this->pageTitle = __('Users', true);
        $this->layout = 'user_portlet';
    }

    function checkemail() {

        if(empty($_REQUEST['email'])){
            $this->ajaxOutput(array('error'=>lang('email empty.')));
            exit; // empty email.
        }
        App::uses('Validation', 'Utility');

        if(!Validation::email($_REQUEST['email'])) {
            $this->ajaxOutput(array('error'=>lang('It\'s not a email.')));; // email validate error.
        }
        else{
            $user = $this->User->find('first',array(
                'conditions'=> array('email'=> $_REQUEST['email']),
            ));
            if(!empty($user)){
                $this->ajaxOutput(array('error'=> __('Email is registed.'))); // email used
            }
            else{
                $this->ajaxOutput(array('success'=> __('Email is allowed.')));
                // email is not used.
            }
        }        
        exit;
    }

    function checkusername() {
        // print_r($this->data);
        // $user = $this->User->findByUsername($username);
        // print_r($user);
        exit;
    }
    
    function send_msg($exists = 0) {
        
        $salt = Configure::read('User.sms_salt');
        $is_sign_mode = false;
        if(empty($_REQUEST['mobile'])) {
            $error_msg = array('ret'=>-1,'error'=>'请输入手机号');
        }
        elseif( !empty($salt) && !empty($_REQUEST['sign']) && !empty($_REQUEST['timestamp']) && (time() - $_REQUEST['timestamp']) < 600 ) {
            
            if($_REQUEST['sign'] != md5($_REQUEST['timestamp'].$_REQUEST['session_id'].$salt) ){
                $error_msg = array('ret'=>-1,'msg'=>'参数错误');
            }
            else{
                // 正确时，无需验证capcha，手机端免输入图片验证码获取手机短信
                $is_sign_mode = true;
            }
        }
        elseif(empty($_POST['captcha'] ) || strtolower($_POST['captcha']) != strtolower($this->Session->read('captcha'))) {
    		$error_msg = array('ret'=>-1,'msg'=>'您的验证码错误');
    	}
    	
    	if(!empty($error_msg)) {
    		$this->ajaxOutput($error_msg);
    		exit;
    	}
    	else{
    		
    		$user = $this->User->find('first',array(
    				'conditions'=> array('mobile'=> $_REQUEST['mobile']),
    		));
    		
    		if( empty($_REQUEST['skip_check']) ) {
    		    if(!$exists && !empty($user)) {
    		        $this->ajaxOutput(array('ret'=> -1, 'msg'=> '手机号已经注册过了'));
    		        exit;
    		    }
    		    if($exists && empty($user)) {
    		        $this->ajaxOutput(array('ret'=> -1, 'msg'=> '手机号没有注册，请检查手机号是否正确。'));
    		        exit;
    		    }
    		}

    		App::uses('Yunpian', 'Lib');
    		$code = random_str(4,'num');
    		
    		$sms_appkey = Configure::read('User.sms_key');
    		if( $sms_appkey ) {
    		    Yunpian::$apikey = $sms_appkey;
    		}
    		$sms_captpl = Configure::read('User.sms_captpl');
    		
    		if( $sms_captpl ) {
    		    $sms_captpl = sprintf($sms_captpl,$code);
    		}
    		else{
    		    $sms_captpl = '【135编辑器】您的验证码是'.$code.'，如非本人操作，请忽略。';
    		}
   			$result = Yunpian::single_send($_POST['mobile'],$sms_captpl);
   			
    		if(isset($result['code']) && $result['code']==0 ) {
    		    $this->loadModel('MobileCaptcha');
    		    $this->MobileCaptcha->save(array(
    		        'mobile' => $_POST['mobile'],
                    'code' => $code,
                ));

    		    $ret_msg = array('ret'=> 0,'msg'=>'短信已发送，请注意查收');
    		    if($is_sign_mode) {
    		        $ret_msg['code'] = $code;
    		    }
    			$this->ajaxOutput($ret_msg);
    		}
    		else{
    			CakeLog::error("User->send_msg yunpian error:".var_export($result,true));
    			$this->ajaxOutput(array('ret'=> -1, 'msg'=> '短信发送失败，原因为：'.$result['msg'].'。'.$result['detail']));
    		}
    		exit;
    	}
    }

    function register($invite_code = '' ) {
        $this->pageTitle = __('Register');
        
        $this->layout = 'default';
        
        if($this->currentUser['id']) {
            $this->Session->setFlash('您已经登录了,若要重新注册请先退出登录');
            $this->redirect('/');
        }
        
        if ( !empty($this->data) && !empty($this->data['User']['mobile']) && !empty($this->data['User']['password']) ) {
            $this->autoRender = false;
            $invite_code = $_POST['invite_code'] ? $_POST['invite_code'] : $invite_code;
            
            $this->User->create();
            $this->data['User']['id'] = null;
            $this->data['User']['role_id'] = Configure::read('User.defaultroler'); // Registered defaultroler
            $this->data['User']['activation_key'] = md5(uniqid());
            $this->data['User']['invite_code'] = md5(uniqid());
	        $this->data['User']['password'] = Security::hash($this->data['User']['password'] , null, true);

	        if(strlen($this->data['User']['password']) < 6 ) {
	            $has_error = true;
	            $error_msg = __('Password is at least 6 characters.');
	            $this->Session->setFlash( $error_msg );
	        }
	        /*elseif(strlen($this->data['User']['email']) > 32 ) {
	            $has_error = true;
	            $error_msg = __('邮箱长度不超过32位字符。');
	            $this->Session->setFlash( $error_msg );
	        }*/
            elseif ($this->data['User']['password'] != Security::hash($this->data['User']['password_confirm'], null, true)) {
            	$error_msg = __('Two password is empty or not equare.');
                $this->Session->setFlash( $error_msg );
            }
            else {
                $has_error = false;
                $this->data['User']['id'] = null;

                $this->loadModel('MobileCaptcha');
                $db_captcha = $this->MobileCaptcha->getCodes( $this->data['User']['mobile'] );
                $this->data['User']['captcha'] = strtolower($this->data['User']['captcha']);
                if( empty($this->data['User']['captcha'] ) || !in_array( $this->data['User']['captcha'],$db_captcha ) ) { //strtolower($this->data['User']['captcha']) != strtolower($this->Session->read('captcha'))) {
                    $has_error = true;
                    $error_msg = __('Captcha error.');
                }
                else if(!empty($this->data['User']['mobile'])){
                	$phone_used = $this->User->find('first',array(
                			'conditions'=>array('mobile' => $this->data['User']['mobile']),
                	));
                	$this->data['User']['username'] = substr($this->data['User']['mobile'],-4);
                	if($phone_used){
                		$has_error = true;
                		$error_msg = __('这个手机号以及注册过了');
                	}
                }
                /*elseif(!empty($this->data['User']['email'])){
                    $email_used = $this->User->find('first',array(
                        'conditions'=>array('email' => $this->data['User']['email']),
                    ));
                    if($email_used){
                        $has_error = true;
                        $error_msg = __('Email has registered,do you forget password?');
                    }
                    if(empty($this->data['User']['username'])){                    	
                        $this->data['User']['username'] = $this->data['User']['email'];
                    }*/
                    /*if($has_error == false && defined('UC_APPID')) {
                        App::import('Vendor', '',array('file' => 'uc_client'.DS.'client.php'));                 
                        $username =  $this->data['User']['username'];
                        if(UC_DBCHARSET =='gbk'){
                            App::uses('Charset', 'Lib');
                            $username = Charset::utf8_gbk($username);
                        }
                        $uid = uc_user_register($username,$src_password, $this->data['User']['email'],'','', $this->request->clientIp());
                        if($uid<=0){
                            if($uid == -1) {
                                $error_msg = '用户名不合法';
                            } elseif($uid == -2) {
                                $error_msg = '包含不允许注册的词语';
                            } elseif($uid == -3) {
                                $error_msg = '用户名已经存在';
                            } elseif($uid == -4) {
                                $error_msg = 'Email 格式有误';
                            } elseif($uid == -5) {
                                $error_msg = 'Email 不允许注册';
                            } elseif($uid == -6) {
                                $error_msg = '该 Email 已经被注册';
                            } else{
                                $error_msg = '未知错误';
                            }
                            $has_error = true;
                        }
                        else if($uid>0){
                            $this->data['User']['id'] = $uid;
                        }
                    }*/
                //}
                else
                {
                    $has_error = true;
                    $error_msg =  __('Please input your email at first.');
                }
                
                if ($has_error==false && ( !empty($this->data['User']['email']) || !empty($this->data['User']['mobile'])  ) && $this->User->save($this->data)) {
                    /* 成功注册 */
//	                $this->autoRender = false;
					if(empty($this->data['User']['id'])){
                		$this->data['User']['id'] = $this->User->getLastInsertID();
					}
					
					$data = $this->User->getUserInfo( $this->data['User']['id'] );
					$this->Session->write('Auth.User', $data['User']);
					
					$this->Hook->loadhook('ScoreHook');
					$this->Hook->call('registerSuccess',array( $this->data['User']['id'],$this->data['User'] ) );

					$this->loadModel('MobileCaptcha');
                    $this->MobileCaptcha->remove($this->data['User']['mobile'],$this->data['User']['captcha']);

					if( $invite_code ) { //使用邀请链接注册
					    $invite_user = $this->User->find('first',array('conditions' => array('invite_code'=> $invite_code)));
					    
					    if( !empty($invite_code) ) {
					        $this->loadModel('InviteLog');
					        $this->InviteLog->save(array(
					            'user_id' => $this->data['User']['id'],
					            'invitor_id' => $invite_user['User']['id'],
					            'status' => 0,
					        ));
					    }
					    
					    $this->ScoreHook = $this->Components->load('ScoreHook');
					    $this->ScoreHook->addScore($this,$this->data['User']['id'],$invite_user['User']['id'],'User','invited');
					    $this->ScoreHook->addScore($this,$invite_user['User']['id'],$this->data['User']['id'],'User','invite');
					    
					    $this->User->extendRole($this->data['User']['id'],8,1); //注册人加会员
					    $this->User->extendRole($invite_user['User']['id'],8,1); // 发送邀请人加会员
					}
					
                    if ( Configure::read('User.welcome_email') && $this->data['User']['email'] ) {
                        $this->Email->from = Configure::read('Site.title').' '. '<' . Configure::read('Site.email') . '>';
                        $this->Email->to = $this->data['User']['email'];
                        $this->Email->subject =  Configure::read('Site.title').__('Please activate your account');
                        $this->Email->template = 'register';
                        $this->data['User']['password'] = null;
                        $this->set('user', $this->data);
                        $this->Email->send();
                    }
                    
                    if( Configure::read('Easemob.open') == 1) {
                        App::uses('EasemobUtility','Utility');
                        EasemobUtility::register($this->data['User']['id'], $this->data['User']['invite_code'], $this->data['User']['username']);
                    }
                    
                    
                    if ($this->RequestHandler->accepts('json') || $this->request->is('ajax') || isset($_REQUEST['inajax'])) {
                        $successinfo = array(
                            'ret' => 0,
                            'msg' => __('registe success'), 
                            'userinfo' => array(
                                'id' => $this->data['User']['id'],
                                'username' => $this->data['User']['username'],
                                'code' => $this->data['User']['invite_code'],
                            ),
                            'tasks'=>array(array('dotype'=>'reload')),
                        );

                        $this->ajaxOutput($successinfo);
                        exit;
                    }
                    else{
                        $this->redirect('/');
                    }
                    
                } else {
//                 	print_r($this->User->validationErrors);
                	if(empty($error_msg)) {
                		$error_msg = __('用户创建错误，请联系管理员。');
                	}
                    $this->Session->setFlash($error_msg);
                }
            }
            if ($has_error==true && $this->RequestHandler->accepts('json') || $this->request->is('ajax') || isset($_REQUEST['inajax'])) {
                $errorinfo = array(
                    'ret' => -1,
                    'msg' => $error_msg, 
                    'tasks' => array(
                		array('dotype' => 'html', 'selector' => '#register_errorinfo', 'content' => $error_msg),
                		array('dotype' => 'jquery','func'=>'removeClass','args'=>'hidden','selector' => '#register_errorinfo'),
                ));
                $this->autoRender = false; // 不显示模板
                $this->ajaxOutput($errorinfo);                
                
                exit;
            }
        } else {            
            $this->Session->delete('Message.flash');
        }
        
        if($invite_code ) {
            $invite_user = $this->User->find('first',array('conditions' => array('invite_code'=> $invite_code)));
            $this->set('invite_user',$invite_user);
            $this->set('invite_code',$invite_code);

            $this->Session->write('Auth.invite_code',$invite_code);
        }
    }
    

    function activateEmail($uid = null, $key = null) {
    	 
    	$this->pageTitle = __('Activate email');
    	 
    	if ($uid == null && $key == null) {
    		$user = $this->Auth->user();
    		if(empty($user['id'])){
    			$this->__message(__("You need to login"), '/');
    		}
    		$this->set('user',$user);
    		if ( $user['status'] == 1) {
    			$this->Session->setFlash(__('Your email is already activated.'));
    		}
    	}
    	elseif($uid=="resend"){
    		$user = $this->Auth->user();
    		if(empty($user['id'])){
    			$this->__message(__("You need to login"), '/');
    		}
    		if($this->sendActiveEmail($user)){
    			$this->redirect('/users/activateEmail');
    		}
    		else{
    			$this->Session->setFlash(__('Email send failed.Please retry or contact with administrator.'));
    		}
    	}
    	else {
    		$user = $this->User->findById($uid);
    		if (!empty($user)) {
    			if($user['User']['status'] == 1){
    				$this->Session->write('Auth.User.status',1);
    				$this->Session->setFlash(__('Your email is already activated.'));
    			}
    			elseif($user['User']['activation_key'] != $key){
    				$this->Session->setFlash('The link has expired.Please retry.');
    			}
    			else{
    				$this->User->id = $user['User']['id'];
    				 
    				$updated = array();
    				$updated['status'] = 1;
    				$updated['activation_key'] = $this->User->escape_string(md5(uniqid()));
    				 
    				if ($this->User->updateAll($updated,array('User.id'=>$uid))) {
    					$this->Session->setFlash(__('Your email is activated success.'));
    					// 更新session
    					$this->Session->write('Auth.User.status',1);
    				}
    				else{
    					$this->Session->setFlash(__('System error.Please retry or contact with administrator.'));
    				}
    			}
    
    			$this->set('user',$user['User']);
    
    		} else {
    			throw new NotFoundException('Error Prams');
    		}
    	}
    }
    
    private function sendActiveEmail($user){ /*内部方法调用，或外部直接调用。不能直接redirect跳转*/
    	App::uses('EmailUtility', 'Utility');
    	$email_sender = new EmailUtility();
    	 
    	if(!is_array($user)){
    		$result = $this->User->findById($user);
    		$user = $result['User'];
    	}
    	if(!empty($user)){
    		$email_options = array(
    				'to' => $user['email'],
    				'subject' => '[' . Configure::read('Site.title') . '] ' . __('Please activate your account'),
    				'template' => 'register',
    				'viewVars' => array('user'=>$user,'activationKey'=> $activationKey),
    		);
    		if($email_sender->send($email_options)){
    			//$this->Session->setFlash(__('Email send success.'));
    			return true;
    		}
    		else{
    			//$this->Session->setFlash(__('Email send failed.Please retry or contact with administrator.'));
    		}
    	}
    	return false;
    }
    
    function activate($username = null, $key = null) {

        if ($username == null || $key == null) {
            $user = $this->Auth->user();
            if (!empty($user['User']) && $user['User']['status'] == 0) {
                //'您的用户没有激活';
                //exit;
            } else {
                $this->redirect(array('action' => 'login'));
            }
        } else {
            if ($this->User->hasAny(array(
                        'User.username' => $username,
                        'User.activation_key' => $key, 'User.status' => 0,)
            )) {
                $user = $this->User->findByUsername($username);
                $this->User->id = $user['User']['id'];
                $this->User->saveField('status', 1);
                $activation_key = md5(uniqid());
                $this->User->saveField('activation_key', $activation_key);

                // 更新cookie与session
                $user['User']['status'] = 1;
                $user['User']['activation_key'] = $activation_key;
                $this->Session->write('Auth.User', $user['User']);
                $this->Cookie->write('User', $user['User']);
            } else {
                //exit;
                $this->__message('激活链接已失效，请重新获取。', array('action' => 'activate'));
                //$this->redirect(array('action' => 'activate'));
            }
        }
    }

    function edit($id=null) {
    	$this->pageTitle = __('Edit Profile');
        $userinfo = $this->Auth->user();
        if ($userinfo['id']) {
            $datainfo = $this->User->find('first', array('recursive' => -1, 'conditions' => array('User.id' => $userinfo['id'])));
            if (empty($datainfo)) {
                throw new ForbiddenException(__('You cannot edit this data'));
            }

            if (!empty($this->data)) {
            	unset($this->data['User']['mobile']);
            	
            	$this->data['User']['id'] = $userinfo['id'];            	
                if ($this->{$this->modelClass}->save($this->data)) {
                    $successinfo = array(
                        'ret'=>0,
                        'msg' => __('Edit success'), 
                        'actions' => array('OK' => 'closedialog'),
                        'data' => array(
                            'sex' => $this->data['User']['sex'],
                            'mobile' => $datainfo['User']['mobile'],
                            'email' => $datainfo['User']['email'],
                            'avatar' => $datainfo['User']['avatar'],
                            'sex' => $this->data['User']['sex'],
                            'username' => $this->data['User']['username'],
                        ),
                    );
                    
                    if ($this->RequestHandler->accepts('json') || $this->request->is('ajax') || isset($_REQUEST['inajax'])) {
                        $this->ajaxOutput($successinfo);
                        exit;
                    }
                } else {
                    if ($this->RequestHandler->accepts('json') || $this->request->is('ajax') || isset($_REQUEST['inajax'])) {
                        $this->ajaxOutput(array('ret'=>-1,'msg'=>'save error'));
                        exit;
                    }
                    $this->__message(__('The Data could not be saved. Please, try again.'));
                }
                
            }
            if (empty($this->data)) {
                $this->data = $datainfo;
            }
        } else {
//             $this->Session->setFlash(__('You are not authorized to access that location.', true));
            $this->redirect(array('action' => 'login'));
        }
    }

    function editpassword() {
    	
    	$this->pageTitle = __('Edit Password');
    	
        $userinfo = $this->Auth->user();
        $uid = $userinfo['id'];
        if ( !$uid ) {
            $this->Session->setFlash(__('You are not authorized to access that location.'));
            $this->redirect(array('action' => 'login'));
        }
        if (!empty($this->data) && isset($this->data['User']['password'])) {
            $before_edit = $this->{$this->modelClass}->read(null, $userinfo['id']);

            $ajax_data = array();
            if ($before_edit['User']['password'] == Security::hash($this->data['User']['password'], null, true)) {

                if (!empty($this->data['User']['new_password']) && $this->data['User']['new_password'] == $this->data['User']['password_confirm']) {
                	$updated = array();
                    $updated['password'] = $this->User->escape_string(Security::hash($this->data['User']['new_password'], null, true));
                    $updated['activation_key'] = $this->User->escape_string(md5(uniqid()));
					
                    // User使用save修改数据时，aro表的left,right的值都变成0了，导致权限获取错误。用户信息修改时，都使用updateAll
                    if ($this->User->updateAll($updated,array('User.id'=> $uid))) {
                        $this->Session->setFlash(__('Password is updated success.'));
                        $ajax_data = array('ret'=> 0,'msg'=>__('Password is updated success.'));
                    }
                } else {
                    $ajax_data = array('ret'=> -1,'msg'=>__('Two password is not equare or empty.'));
                    $this->Session->setFlash(__('Two password is not equare or empty.'));
                }
            } else {
                $ajax_data = array('ret'=> -1,'msg'=>__('Your password is not right.'));
                $this->Session->setFlash(__('Your password is not right.'));
            }
            
            $this->set('ajax_data', $ajax_data);
            $this->set('_serialize', 'ajax_data');
            
        } else {
            $this->Session->delete('Message.flash');
        }
        
    }
    
    public function invite($uid = 0 ){

        $this->layout = 'wechat';
        $this->pageTitle = __('My Invites');
        if( empty($uid) ) {
            $uid = $this->currentUser['id'];
            $this->redirect('/users/invite/'.$uid);
        }
        if(empty($uid)) {
            $this->__message('您还没有登录或邀请链接参数错误','',999);
            exit;
        }
        $userinfo = $this->User->find('first',array('conditions'=> array('User.id'=>$uid),'recursive'=>-1));
        $this->set('userinfo',$userinfo);
        $this->set('invite_code',$userinfo['User']['invite_code']);
    }
    
    function avatar(){        
        $uid = $this->currentUser['id'];        
        if($uid && $_FILES['avatar'] ) {
            $object_name = '/avatar'.getAvatarPath($uid).$uid.'_0.jpg';
            App::uses('CrawlUtility', 'Utility');
            $avatar_url = CrawlUtility::saveToAliOss($_FILES['avatar']['tmp_name'], $object_name,true,false,$_FILES['avatar']['type']);
            if( $avatar_url ){
                $avatar_url .= '?_='.random_str(4); //图片地址固定不变，增加一个随机的参数去除缓存的影响
                $this->User->updateAll(array(
                    'avatar'=> $this->User->escape_string($avatar_url),
                ),array('id' => $uid));
                $this->Session->write('Auth.User.image',$avatar_url);
            
                $this->ajaxOutput(array('ret'=>0,'msg'=>'success','url'=>$avatar_url));
                exit;
            }
            else{
                $this->ajaxOutput(array('ret'=>-1,'msg'=>'upload failed'));
                exit;
            }
        }
        else{
            $this->ajaxOutput(array('ret'=>-1,'msg'=>'please upload file.'));
            exit;
        }
    }
    
    public function activeVip() {
        
        $codeNum = $this->data['User']['code'] ? $this->data['User']['code'] : $_REQUEST['code'];
        
        $this->pageTitle =  __('激活VIP邀请码');
        
        if( !empty($codeNum) ) {
            $this->loadModel('InviteCode');
            $this->loadModel('InviteCodeLog');

            $code = $this->InviteCode->find('first',array(
              'conditions'=> array('name' => $codeNum,'end >' => date('Y-m-d H:i:s') )
            ));
            
            if(!empty($code) && $code['InviteCode']['used'] < $code['InviteCode']['allow_nums'] ) {
                //$code['InviteCode']['role_id'],$code['InviteCode']['role_days'];
//                 if($code['InviteCode']['role_id'] < 3) { // 
//                     $this->__message('VIP邀请码错误，用户角色类型需大于3，请联系管理员','/users/activeVip',5,-1);
//                 }
                
                $used = $this->InviteCodeLog->find('first',array(
                    'conditions'=> array('user_id' => $this->currentUser['id'],'code_id' => $code['InviteCode']['id'] )
                ));
                if( !empty($used) ) {
                    $this->__message('您已经激活使用过这个批次的VIP邀请码了，同一批次的VIP邀请码一个人只能使用一次。','/users/activeVip',5,-1);
                }
                else{
                    $this->User->extendRoleDays($this->currentUser['id'],$code['InviteCode']['role_id'],$code['InviteCode']['role_days']);
                    
                    //$code['InviteCode']['used'] = 1;
                    //$code['InviteCode']['user_id'] = $this->currentUser['id'];
                    //$code['InviteCode']['used_time'] = date('Y-m-d H:i:s');
                    $this->InviteCode->updateAll( array('used'=>'used+1'),array( 'id'=> $code['InviteCode']['id'] ) );
                    $this->InviteCodeLog->save(array(
                        'code_id' => $code['InviteCode']['id'],
                        'user_id' => $this->currentUser['id'],
                        'created' => date('Y-m-d H:i:s'),
                    ));

                    if($code['InviteCode']['company_id']) {
                        
                        $this->loadModel('Role');
                        $RoleInfo = $this->Role->find('first',array('conditions'=>array('id'=>$code['InviteCode']['role_id'])));
                        
                        $role_company = Configure::read('Role.defulat_company'); // 角色默认加入的团队。 baleka，机构经理与教师除了固有团队外，都默认额外再加了一个群组。
                        
                        $role_company_arr = optionstr_to_array($role_company);
                        
                        $companyids = array($code['InviteCode']['company_id']);
                        if($role_company_arr[$code['InviteCode']['role_id']] && $code['InviteCode']['company_id'] != $role_company_arr[$code['InviteCode']['role_id']]) {
                            $companyids[] = $role_company_arr[ $code['InviteCode']['role_id'] ];
                        }
                        
                        if(  Configure::read('Easemob.open') == 1 ) {
                            $this->loadModel('Company');
                            $companys = $this->Company->find('all',array(
                                'conditions' => array(
                                    'id' => $companyids,
                                ),
                                'fields' => array(
                                    'id','name','groupid',
                                ),
                                'order' => 'Company.id desc',
                                'recursive' => -1,
                            ));
                            foreach($companys as $c) {                                
                                if($c['Company']['groupid']) { // 加入群聊
                                    App::uses('EasemobUtility','Utility');
                                    $result = EasemobUtility::group_member( $c['Company']['groupid'],$this->currentUser['id'] );
                                    CakeLog::debug("join easemob group member.".var_export($result,true));
                                }
                            }
                        }
                        
                        foreach($companyids as $company_id) {
                            $this->loadModel('CompanyMember');
                            $isMember = $this->CompanyMember->find('first',array(
                                'conditions' => array(
                                    'company_id' => $company_id,
                                    'user_id' => $this->currentUser['id'],
                                ),
                            ));
                            if(empty($isMember)) {
                                $this->CompanyMember->create();
                                $this->CompanyMember->save(array(
                                    'company_id' => $company_id,
                                    'user_id' => $this->currentUser['id'],
                                    'role_id' => $code['InviteCode']['role_id'],
                                    'status' => 1,
                                ));
                            }
                            else{
                                // 否则修改激活的角色。
                                $this->CompanyMember->save(array(
                                    'id' => $isMember['CompanyMember']['id'],
                                    'company_id' => $company_id,
                                    'user_id' => $this->currentUser['id'],
                                    'role_id' => $code['InviteCode']['role_id'],
                                    'status' => 1,
                                ));
                            }
                        }
                    }
                    
                    $userinfo = $this->User->getUserInfo($this->currentUser['id']);
                    $this->Session->write('App.User',$userinfo['User']);

                    $this->loadModel('Shortmessage');
                    $this->Shortmessage->send('VIP权限激活成功','尊敬的用户您好，您已成功使用激活码“'.$codeNum.'”激活了VIP会员权限。您可以进入<a href="/users/permission" target="_blank">我的权限</a>查看。',0,$this->currentUser['id']);

                    if ($this->RequestHandler->accepts('json') || $this->request->is('ajax') || isset($_REQUEST['inajax'])) {
                        
                        $ret_company = array();
                        if(is_array($companys)){
                            foreach($companys as $c) {
                                if($code['InviteCode']['company_id'] == $c['Company']['id'] ){
                                    $c['Company']['role_id'] = $code['InviteCode']['role_id'];
                                }
                                $ret_company[] = $c['Company'];
                            }
                        }

                        $this->ajaxOutput(array(
                            'ret' => 0,
                            'msg' => 'VIP邀请码激活成功，进入我的权限查看。',
                            'tasks'=> array(array('dotype'=>'reload')),
                            'role_id' => $code['InviteCode']['role_id'],
                            'Company' => $ret_company,
                            'Role' => $RoleInfo['Role'],
                            'User' => $userinfo['User'],
                        ));
                    }
                }
                $this->__message('VIP邀请码激活成功，进入我的权限查看。','/users/permission',5,0);                
            }
            else{
                $this->__message('VIP邀请码已经被使用过了或者已经过期。','/users/activeVip',5,-1);
            }
        }
    }
    

    function forgot() {
    	$this->layout = 'default';
    	$this->pageTitle = __('Forget Password');
    
    	if($this->currentUser['id']){
    		$this->__message(__("You are current login with <B>%s</B>,please logout at first.",$this->currentUser['username']), '/');
    	}
    
    	if (!empty($this->data) && isset($this->data['User']['email'])) {
    		$user = $this->User->findByEmail($this->data['User']['email']);
    		if (!isset($user['User']['id'])) {
    			$this->redirect(array('action' => 'login'));
    		}
    		else{
    			$this->User->id = $user['User']['id'];
    			$activationKey = md5(uniqid());
    			 
    			$this->User->updateAll(array( 'activation_key' => $this->User->escape_string($activationKey) ),array('User.id'=> $user['User']['id'] ));
    			 
    			App::uses('EmailUtility', 'Utility');
    			$email_sender = new EmailUtility();
    			$email_options = array(
    					'to' => $user['User']['email'],
    					'subject' => '[' . Configure::read('Site.title') . '] ' . __('Reset Password'),
    					'template' => 'forgot_password',
    					'viewVars' => array('user'=>$user['User'], 'activationKey'=>$activationKey),
    			);
    			/* send未使用第二个参数传送smtp账号信息，发送邮件使用Smpt表随机取一条发送 */
    			if($email_sender->send($email_options)){
    				$this->__message(__('Email send success.Please click the link in the email.'));
    			}
    			else{
    				$this->__message(__('Email send failed.Please retry or contact with administrator.'));
    			}
    		}
    	}
    }
    
    function unoauth( $id ){
        $this->loadModel('Oauthbind');
        $oauth = $this->Oauthbind->find('first',array(
            'conditions' => array('id' => $id,'user_id'=> $this->currentUser['id']),
        ));
        if(empty($oauth)) {
            $this->__message('参数错误');
        }
        else{
            if(empty($this->currentUser['mobile'])){
                $this->__message('请先绑定手机号，绑定手机号后可解除第三方账号');
            }
            else{
                $this->Oauthbind->deleteAll(array('Oauthbind.id' => $id), false, true);
                $this->__message('已成功解绑','/users/index');
            }
        }
    }
    
    function bindMobile(){
        
        $this->pageTitle = __('Bind Mobile');
    	
    	if(!empty($this->currentUser['mobile']) && is_phone_number($this->currentUser['mobile'])) {
    		$this->__message(__("您的账号已经绑定过手机号了。"), '/users/index',5);
    	}
    	
    	if ( $this->currentUser['id'] && !empty($this->data) && !empty($this->data['User']['mobile']) ) {
    	    $this->loadModel('MobileCaptcha');
            $db_captcha = $this->MobileCaptcha->getCodes( $this->data['User']['mobile'] );

            $this->data['User']['captcha'] = strtolower($this->data['User']['captcha']);
    		if( empty($this->data['User']['captcha'] ) || !in_array( $this->data['User']['captcha'],$db_captcha ) ) { //strtolower($this->data['User']['captcha']) != strtolower($this->Session->read('captcha'))) {
    			$this->__message(__("手机验证码错误"));
    		}
    		else if ($this->User->updateAll(array('mobile'=>$this->data['User']['mobile']),array('User.id'=>$this->currentUser['id']))) {
                $this->MobileCaptcha->remove($this->data['User']['mobile'],$this->data['User']['captcha']);
    			$this->currentUser['mobile'] = $this->data['User']['mobile'];
    			if( $this->Session ) {
                    $this->Session->write('Auth.User',$this->currentUser);
                    $this->Session->setFlash(__('已成功绑定手机号'));
                }
    			$this->redirect("/users/index");
    		}
    		else{
                $this->__message(__('Your password is reset error.Please retry or contact with administrator.'));
    		}
    	}
    }
    
    function resetByMobile() {
    	$this->pageTitle = __('手机号重置密码');
    	$this->layout = 'default';
    	
    	if ( !empty($this->data) && !empty($this->data['User']['mobile']) && isset($this->data['User']['password'])) {

    		$user = $this->User->find('first', array(
    				'conditions' => array(
    					'User.mobile' => $this->data['User']['mobile'],
    				),
    		));
    		if (!isset($user['User']['id'])) {
    			$this->__message(__("该手机号的用户没有找到，请确认手机号是否正确."),'/users/resetByMobile',5,-1);
    		}

            $this->loadModel('MobileCaptcha');
            $db_captcha = $this->MobileCaptcha->getCodes( $this->data['User']['mobile'] );

            $this->data['User']['captcha'] = strtolower($this->data['User']['captcha']);

            if( empty($this->data['User']['captcha'] ) || !in_array( $this->data['User']['captcha'],$db_captcha ) ) { //strtolower($this->data['User']['captcha']) != strtolower($this->Session->read('captcha'))) {
                $this->__message(__("手机验证码错误"),'/users/resetByMobile',5,-1);
            }


            $updated = array();
    		$updated['password'] = $this->User->escape_string(Security::hash($this->data['User']['password'], null, true));
    		$updated['activation_key'] = $this->User->escape_string(md5(uniqid()));
    
    		if ($this->User->updateAll($updated,array('User.id'=>$user['User']['id']))) {
                $this->MobileCaptcha->remove($this->data['User']['mobile'],$this->data['User']['captcha']);
    			$this->__message(__('Reset password success.'),"/users/login",5,0);
    		}
    		else{
    		    $this->__message(__('Your password is reset error.Please retry or contact with administrator.'),null,5,-1);
    		}
    	}
    }
    
    function reset($uid = null, $key = null) {
    	$this->pageTitle = __('Reset Password');
    	$this->layout = 'default';
    
    	if ($uid == null || $key == null) {
    		throw new NotFoundException('Error Prams');
    	}
    
    	$user = $this->User->find('first', array(
    			'conditions' => array(
    					'User.id' => $uid,
    					//'User.activation_key' => $key,
    			),
    	));
    	if (!isset($user['User']['id'])) {
    	    $this->__message(__("该用户没有找到，请与管理员联系."), '/',900);
    	}
    	if (empty($user['User']['activation_key']) || $user['User']['activation_key'] != $key) {
    	    $this->__message(__("找回密码的链接已失效，该链接只可使用一次。请重新找回密码。"), '/users/forgot',10);
    	}
    
    	if (!empty($this->data) && isset($this->data['User']['password'])) {
    		$updated = array();
    		$updated['password'] = $this->User->escape_string(Security::hash($this->data['User']['password'], null, true));
    		$updated['activation_key'] = $this->User->escape_string(md5(uniqid()));
    
    		if ($this->User->updateAll($updated,array('User.id'=>$uid))) {
    			$this->Session->setFlash(__('Reset password success.'));
    			$this->redirect("/");
    		}
    		else{
    			$this->Session->setFlash(__('Your password is reset error.Please retry or contact with administrator.'));
    		}
    	}
    	$this->set(array('user'=>$user,'uid'=>$uid, 'username'=> $user['User']['username'], 'key'=>$key));
    }
    
    function unauthorized(){
    	
    }
    
    function info(){
        $salt = Configure::read('User.sms_salt');
        if( !empty($_REQUEST['user_id']) && !empty($_REQUEST['sign']) && !empty($salt) && !empty($_REQUEST['timestamp']) && (time() - $_REQUEST['timestamp']) < 3600  ){
            if($_REQUEST['sign'] != md5($_REQUEST['timestamp'].$_REQUEST['user_id'].$salt) ){
                echo json_encode(array('ret'=>-1,'msg'=>'error params'));
                exit;
            }
            else{
                // 正确时，无需验证capcha，手机端免输入图片验证码获取手机短信
                $info = $this->User->getUserInfo( $_REQUEST['user_id'] );
                $info['ret'] = 0;
                //$info['Role'] = $info['User']['Role'];
                //$info['Oauthbind'] = $info['User']['Oauthbind'];
                unset($info['User']['Role']);unset($info['User']['Oauthbind']);
                unset($info['User']['password']);
                $this->ajaxOutput($info);
            }
        }
        else if( $this->currentUser['id'] ) {
            $info = $this->User->getUserInfo($this->currentUser['id']);
            $info['ret'] = 0;
            $info['uid'] = $this->currentUser['id'];
            //$info['Role'] = $info['User']['Role'];
            //$info['Oauthbind'] = $info['User']['Oauthbind'];
            unset($info['User']['Role']);unset($info['User']['Oauthbind']);
            unset($info['User']['password']);
            $this->ajaxOutput($info);
        }
        echo json_encode(array('ret'=>-133109,'msg'=> 'session_id已过期，登录失效' ));
        exit;
    }
    
    function avatars() {
        $salt = Configure::read('User.sms_salt');
        if( !empty($salt) && !empty($_REQUEST['users']) && !empty($_REQUEST['sign']) && !empty($_REQUEST['timestamp']) && (time() - $_REQUEST['timestamp']) < 600 ) {
        
            if($_REQUEST['sign'] != md5($_REQUEST['timestamp'].$salt) ){
                echo json_encode(array('ret'=>-1,'msg'=>'error params'));
                exit;
            }
            else{
                if(is_array( $_REQUEST['users'] )) {
                    $users = $_REQUEST['users'];
                }
                else{
                    $users = @explode(',',$_REQUEST['users']);
                }
                
                // 正确时，无需验证capcha，手机端免输入图片验证码获取手机短信
                $userlist = $this->User->find('all',array(
                    'conditions'=> array( 'id' => $users ) ,
                    'fields' => array('id','username','avatar'),
                    'recursive' => -1,
                    'limit' => 500,
                ));
                
                $info = array();
                $info['ret'] = 0;
                $info['count'] = count($userlist);
                $info['data'] = array();
                foreach($userlist as $u) {
                    $info['data'][] = $u['User'];
                }
                
                $this->ajaxOutput($info);
            }
        }
        else{
            echo json_encode(array('ret'=>-1,'msg'=>'error params'));
            exit;
        }
    }

    function login() {
    	
    	$this->pageTitle = __('Sign In To Your Account');
    	$this->layout = 'default';
    	
        $redirect = $this->data['User']['referer'] ? $this->data['User']['referer'] : $_REQUEST['referer'];
        if(empty($redirect)){
            $redirect = $this->Session->read('Auth.redirect');
            if( empty($redirect) ) {
                if( $_SERVER['HTTP_REFERER'] && strpos($_SERVER['HTTP_REFERER'],'/users/login' )===false ) { //不为登录页时，直接跳转到referer
                    $redirect = $_SERVER['HTTP_REFERER']; //直接跳转到整个referer地址。不需要去掉host,可能是多点登录的其余站点。
                }
            }
            if( empty($redirect) || $redirect == '/users/login') {
                $redirect = '/';
            }
        }
        $success = false;
        
        if(empty($this->data) && $this->request->query['data']){ //get 方式传入时,phonegap
        	$this->data = $this->request->query['data'];
        }
        
        if( $_GET['a']=='appsync' && !empty($_GET['appkey']) && !empty($_GET['sign']) && !empty($_GET['u']) ){
            $this->loadModel('UcenterApp');
            $uapp = $this->UcenterApp->find('first',array(
                'conditions'=>array('appkey'=>$_REQUEST['appkey'])
            ));
            
            if( !empty($uapp) ) {
            	$sign = md5($_GET['appkey'].$uapp['UcenterApp']['secretkey'].$_GET['u'].$_GET['ts']);
            	// 校验通过，则设置用户的编号
            	if( $sign == $_GET['sign'] ) {
            		$u = base64_decode($_GET['u']);
            		$id = Security::rijndael($u,$uapp['UcenterApp']['secretkey'],'decrypt');
            		if($id) {
            			$this->User->recursive = 1;
                        $userinfo = $this->User->getUserInfo($id);
            			if(!empty($userinfo['User'])) {
            				$this->Session->write('Auth.User',$userinfo['User']);
            				$this->Session->write('Auth.User.Role',$userinfo['Role']);
            			}
            		}
            	}
            }
        }

        $id = $this->Auth->user('id');
        $is_new_user = false; $loged_by_cookie = false;
        if( empty($id) && empty($_POST) && isset($_COOKIE['MIAOCMS']) && $_COOKIE['MIAOCMS']['Auth']['User']){
            
        	//     	if( isset($_COOKIE['MIAOCMS']) && $_COOKIE['MIAOCMS']['Auth']['User']){
        	$user = $this->Cookie->read('Auth.User'); // cookie有效时间，强制登录。cookie登录的不更新cookie
            $c_t = time() - 7*24*3600;
        	if(is_array($user) && $user['c_t']> $c_t && intval($user['id']) > 0) { // cookie正常解析数据，登录cookie信息对应的用户
        	    $id = intval($user['id']);
        	    $this->User->recursive = 1;
                $loged_by_cookie = true;
        	    $userinfo = $this->User->getUserInfo( $id );        	     
        	    $this->Session->write('Auth.User',$userinfo['User']);
        	}
        	else{
        	    unset($user,$_COOKIE['MIAOCMS']['Auth']['User']);
        	    $this->Cookie->delete('Auth.User');
        	}
        }

        $client_ip = $this->request->clientIp();

        if ( $id ) { //已经登录的
        	// $user = $this->Auth->user(); // 重新从库中查， 更新用户角色信息。
        	
            $this->Session->delete('User'); //切换账号或登录成功时删错临时的session信息。如User.wxes等
        	
            $this->User->id = $id;
            $updated = array(
                'client_ip' => "'".$client_ip."'",
                'last_login' => "'".date('Y-m-d H:i:s')."'"
            );
            if( $userinfo['User'] && empty($userinfo['User']['invite_code']) ){
	            $invite_code = md5(uniqid());
	            $updated['invite_code']= "'".$invite_code."'";	            
	            $this->Session->write('Auth.User.invite_code', $invite_code);
            }

            $this->User->updateAll($updated,array('User.id' => $id,));
            $success = true;
        }
        elseif (!empty($this->data['User']) && !empty($this->data['User']['email'])&& !empty($this->data['User']['password'])) { // 通过表单登录
            
            $email = $this->data['User']['email'];
            $error_cache_key = 'log_err_nums_'.$email;
            $login_error_nums = Cache::read($error_cache_key);
            if ($login_error_nums < 5 && $this->Auth->login()) {
                $this->User->id = $this->Auth->user('id');
                $this->User->updateAll(array( 'client_ip' => "'".$client_ip."'",'last_login' => "'".date('Y-m-d H:i:s')."'", ),array('User.id' => $this->User->id,));
                
                $success = true;
            }
            elseif($login_error_nums > 0) {
                $login_error_nums ++;
                Cache::increment($error_cache_key);
            }
        }
        elseif (!empty($this->data['User']) && !empty($this->data['User']['mobile'])&& !empty($this->data['User']['capcha']) && $this->Session->read('captcha_mobile') == $this->data['User']['mobile'] ) { // 通过表单登录

            $this->loadModel('MobileCaptcha');
            $db_captcha = $this->MobileCaptcha->getCodes( $this->data['User']['mobile'] );
            $this->data['User']['capcha'] = strtolower($this->data['User']['capcha']);

            if( in_array($this->data['User']['capcha'],$db_captcha) ) { //strtolower($this->data['User']['captcha']) != strtolower($this->Session->read('captcha'))) {
                
                $phone_used = $this->User->getUserByMobile($this->data['User']['mobile']);
                   
                if(empty($phone_used)) {
                    $userinfo = array(
                        'username' => substr($this->data['User']['mobile'],-4),
                        'mobile' => $this->data['User']['mobile'],
                        'password' => Security::hash(random_str(10),null,true),
                        'status' => 0,
                        'role_id' => Configure::read('User.defaultroler'),
                        'activation_key' => md5(uniqid()),
                        'client_ip' => $client_ip,
                        'invite_code' => md5(uniqid()),
                    );
                    if( $this->User->save($userinfo) ) {
                        $is_new_user = true;
                        $success = true;
                        $userinfo['id'] = $this->User->getLastInsertID();
                        if($this->Session) {
                            $this->Session->write('Auth.User',$userinfo);
                        }

                        if( Configure::read('Easemob.open') == 1) {
                            App::uses('EasemobUtility','Utility');
                            EasemobUtility::register($userinfo['id'], $userinfo['invite_code'], $userinfo['username']);
                        }
                        
                        $this->Hook->call('registerSuccess',array( $userinfo['id'], $userinfo ) );
                    }
                    else{
                        $success = false;
                        $error_msg = '手机短信验证码错误';
                    }
                }
                else{ // 用户手机已存在
                    $success = true;
                    if($this->Session) {
                        $this->Session->write('Auth.User', $phone_used['User']);
                    }
                    $this->User->updateAll(array( 'client_ip' => "'".$client_ip."'", 'last_login' => "'".date('Y-m-d H:i:s')."'", ),array('User.id' => $phone_used['User']['id'],));
                }
                $this->MobileCaptcha->remove($this->data['User']['mobile'],$this->data['User']['capcha']);
            }
            else{
                $success = false;
                $error_msg = '手机短信验证码错误';
            }
        }
        elseif (!empty($this->data['User']) && !empty($this->data['User']['mobile']) && !empty($_REQUEST['sign']) && !empty($_REQUEST['timestamp']) ) { // 通过app直接用手机号无密码登录
            // 客户端直接根据手机号来无验证登录
            if(  (time() - $_REQUEST['timestamp']) < 600 ) {
                $salt = Configure::read('User.sms_salt');
                if( $salt && $_REQUEST['sign'] == md5($this->data['User']['mobile'] . $_REQUEST['timestamp'] . $salt ) ){
                    $phone_used = $this->User->getUserByMobile($this->data['User']['mobile']);
                    if(!empty($phone_used)) {
                        $success = true;
                        $this->Session->write('Auth.User',$phone_used['User']);
                        $this->User->updateAll(array( 'client_ip' => "'".$client_ip."'",'last_login' => "'".date('Y-m-d H:i:s')."'", ),array('User.id' => $phone_used['User']['id'],));
                    }
                    else{
                        $success = false;
                        $error_msg = '用户不存在，请核查。';
                    }
                }
                else{
                    $success = false;
                    $error_msg = '密钥错误';
                }
            }
            else{
                $success = false;
                $error_msg = '时间戳错误，已过期。';
            }
        }
        
        if ($success) {
            $user = $this->Auth->user();
//             if( !empty($user) ){
// //                 if( !is_array($user['role_id']) ) {
// //                     $user['role_id'] = array_filter(explode(',',$user['role_id']));
// //                 }
//                 $user['role_id'] = array();
//                 $user['role_id'][] = Configure::read('User.defaultroler') ;
//                 if( !empty($user['Role']) ) {
//                     foreach($user['Role'] as $role) {
//                         $user['role_id'][] = $role['id'];
//                     }
//                 }
//                 $user['role_id'] = array_unique($user['role_id']);
//                 if( !empty($user['UserSetting']['settings']) ) {
//                 	$user['UserSetting'] = json_decode($user['UserSetting']['settings'],true);
//                 }
//                 $this->Session->write('Auth.User',$user);
//             }
            
            /* 成功登录  */
            $this->Hook->loadhook('ScoreHook');
            $hook_results = $this->Hook->call('loginSuccess',array($user));
            $login_score = $hook_results['ScoreHook']; unset($hook_results['ScoreHook']); // 积分数不显示在提示消息中
            $user['login_hook_msg'] = implode('<br/>',$hook_results);
            if($login_score){
            	$user['login_hook_msg'] .= '<BR><BR><div class="alert alert-warning alert-score text-center">'.__('Add score when first login daily').' +'.$login_score.'</div>';
            }
            
            if(defined('UC_APPID')) { //直接登录Ucenter的其它账号
                App::import('Vendor', '', array('file' => 'uc_client' . DS . 'client.php'));
                $user['session_flash'] .= uc_user_synlogin( $user['id'], $user['username'] );
            }
            
            $this->Session->setFlash( __('Login Success').$user['session_flash'].$user['login_hook_msg'] );


            $token = '';

            if($_POST['type'] == 'app') {
                $token = md5($user['id']).random_str(12);
                $this->loadModel('SignToken'); //用户app登录Token
                $this->SignToken->save(array(
                    'id' => $user['id'],
                    'name' => $token,
                    'created' => date('Y-m-d H:i:s'),
                ));
            }
            
            $userinfo = array(
            	'id' => $user['id'],
                'is_new_user' => $is_new_user,
            	'username' => $user['username'],
				'email' => $user['email'],
                'sex' => $user['sex'],
                'avatar' => $user['avatar'],
                'mobile' => $user['mobile'],
                'role_id' => $user['role_id'],
                'roles' => count($user['role_id']),
                'code' => $user['invite_code'],
            	'session_flash' => $user['session_flash'],
            	'login_hook_msg' => $user['login_hook_msg'],
                'token' => $token,
            );
            
            if(!empty($this->data['User']['remember_me'])){
            	$cookietime = 2592000; // 一月内30*24*60*60
            }
            else{
            	$cookietime = 900; // 15分钟
            }
            if(!$loged_by_cookie){ // cookie登录的不记录cookie信息。防止自动延长了cookie的有效期
                $this->Cookie->write('Auth.User',$userinfo, true, $cookietime);
            }
            //$user['Company']
            
            if ($this->RequestHandler->accepts('json') || $this->request->is('ajax') || isset($_REQUEST['inajax'])) {
                // ajax 操作
                $tasks = array(array('dotype'=>'rscallback','callback'=>'loginSuccess'));
                if(is_array($_REQUEST['task'])){
                    $tasks[] = $_REQUEST['task'];
                }
                
                $successinfo = array(
                    'ret' => 0,
                    'msg' => __('Login Success').$user['session_flash'].$user['login_hook_msg'],
                    'userinfo' => $userinfo,
                    'tasks'=> $tasks,
                );
                
                if( !$is_new_user && $_REQUEST['with_more'] ) { //非新用户加载更多信息
                    $user = $this->User->getUserInfo( $user['id'] );
                    
                    unset($user['User']['password']);
                    $userinfo =  array_merge($user['User'],$userinfo);
                    $successinfo['userinfo'] = $userinfo;
                    
                    unset($user['User']);
                    foreach($user as $uk => $uf){
                        if( !empty($uf) ) {
                            $successinfo[$uk] = $uf;
                        }
                    }
                }
                
                $this->autoRender = false; // 不显示模板
                
                if($_REQUEST['return'] == 'html') {
                    $msg = '<div id="login-form">'.__('Login Success').'，请刷新操作。'.$user['session_flash'].$user['login_hook_msg'].'</div>';
                    $this->response->body($msg);
                    $this->response->send();
                }
                else{
                    $this->ajaxOutput($successinfo);
                }
                exit;//echo并 exit退出时，cookie信息未发出，cookie创建失败。
            } else {
				if($user['session_flash'] || $user['login_hook_msg'])
				{
					// UCENTER, auto redirect.
					if(preg_match_all('/<script type="text\/javascript" src="(.+?)"/is',$user['session_flash'].$user['login_hook_msg'],$matches)) {
						foreach($matches[1] as $url)
						{
							$urlinfo = parse_url($url);
							if(strpos($redirect,$urlinfo['host']) !== false) {
								if(strpos($url,'?') !== false){
									$url .= '&redirect='.urlencode($redirect);
								}
								else {
									$url .= '?redirect='.urlencode($redirect);
								}
								$this->redirect($url);
							}
						}
					}
					//$this->__message(__('Login Success'),$redirect,2);
				}
				
				if($_GET['a']=='appsync' && empty($_GET['referer'])){
					$content = $scripts = '';
					if( strpos($_SERVER['HTTP_HOST'],'.135editor.com')!==false ){
						$scripts = 'document.domain="135editor.com";';
					}
					if($_GET['state'] == 'weixinPb'){
					    $redirect = $this->Session->read('Auth.redirect') ? $this->Session->read('Auth.redirect') : '/users/index';
						$this->Session->delete('Auth.redirect');					    
						$this->redirect($redirect);
					    //$content = '已成功登录,窗口将自动关闭。<script>'.$scripts.'window.opener.postMessage("loginSuccess","*");window.close();</script>';
					}
					elseif($_GET['state'] == 'postmsg'){
						$content = '已成功登录,窗口将自动关闭。<script>'.$scripts.'window.opener.postMessage("loginSuccess","*");window.close();</script>';
					}
					elseif($_GET['state'] == 'script'){
						$content = "1;";
					}
					else{
						$content = '已成功登录,窗口将自动关闭。<script>'.$scripts.'window.opener.location.reload(true);window.close();</script>';
					}
					$this->response->body($content);
					$this->response->send();
					exit;
				}
				else{
					$this->Session->delete('Auth.redirect');
					$this->redirect($redirect);
				}				
            }
        } elseif (!empty($this->data['User']) && !empty($this->data['User']['email'])&& !empty($this->data['User']['password'])) {
            $email = $this->data['User']['email'];
            //$error_cache_key = 'log_err_nums_'.md5($email,true);
            if($login_error_nums > 5) {
                    $error_msg = __('Password error more than 5 times. Please retry after 15 minutes.');
            }
            elseif(empty($login_error_nums) && $error_cache_key){
                $hasEmail = $this->User->find('first',array( 'conditions'=> array('email'=> $email ),'fields' => 'id' ) );
                if( !empty($hasEmail) ) {//不存在用户，跳过。存在时设置错误记录. 15分钟内错误超过3次，禁止登录
                    Cache::write($error_cache_key, 1,'default',900);
                }                
            }
            
            if(empty($error_msg)) {
                $error_msg = __('User not exists or password not right');
            }
            
            // login error.
            
            
            if ($this->RequestHandler->accepts('json') || $this->request->is('ajax') || isset($_REQUEST['inajax'])) {
                // ajax 操作
                $errorinfo = array(
                    'ret' => -101,
            		'msg' => $error_msg, 
            		'tasks' => array(
            				array('dotype' => 'html', 'selector' => '#login_errorinfo', 'content' => $error_msg),
            				array('dotype' => 'jquery','func'=>'addClass','args'=>'alert alert-danger', 'selector' => '#login_errorinfo'),
            		));
                
                $this->ajaxOutput($errorinfo);                
                exit;
            } else {
            	$this->Session->setFlash($error_msg);
            }
            //$this->redirect(array('action' => 'forgot'), 401);
        } else {
            if ( $_REQUEST['return'] != 'html' && !empty($_REQUEST['sign']) && ($this->RequestHandler->accepts('json') || $this->request->is('ajax') || isset($_REQUEST['inajax'])) ) {
                // ajax 操作
                $errorinfo = array(
                    'ret' => -102,
                    'msg' => $error_msg,
                );
                $this->ajaxOutput($errorinfo);
                exit;
            }
        }

        $this->Cookie->delete('Auth.User');
        $this->data['User']['referer'] = $redirect;
        $this->set('q_args', $_GET['q_args']);
        
        $this->request->addDetector('weixin', array('env' => 'HTTP_USER_AGENT', 'options' => array('MicroMessenger')));
        if( $this->request->is('weixin') && empty($_REQUEST['nw']) ){
        	$appid = Configure::read('Weixin.AppId');
        	if( $appid && Configure::read('Weixin.AppSecret') ){
        		// 未登录，设置了appid，appSecret打开oauth授权页。snsapi_base,snsapi_userinfo
        		$scope = Configure::read('Weixin.login_scope'); $scope = $scope?$scope:'snsapi_userinfo';

        		//$redirect_url = Router::url('/oauth/weixin/qrcallback',true);
        		$redirect_url = 'http://www.135plat.com/oauth/weixin/pbcallback'; // 微信授权的域名均使用135plat
        		// $redirect_url = 'http://www.135editor.com/oauth/weixin/qrcallback';
        		$authurl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=weixinPb#wechat_redirect';
        		$url = sprintf($authurl,$appid,urlencode($redirect_url),$scope);
        		
        		$this->Session->write('Auth.redirect',$redirect);
        		//$this->Auth->redirect($redirect);// 设置Auth.redirect，登录后跳转回来。$this->request->base.$this->request->url
        		header('Location:'.$url);
        		exit;
        	}
        }
    }
    

    public function getLoginQr( ){
        App::uses('WeixinUtility', 'Utility');;
        WeixinUtility::$appId = Configure::read('Weixin.AppId');
        $scene_id = random_str(9,'num');
        $result = WeixinUtility::qrcode_create($scene_id,'QR_SCENE');
         
        if($result['ticket']) {
            $result['ret'] = 0;
            $result['scene_id'] = $scene_id;
        }
        else{
            $result['ret'] = -1;
            CakeLog::error($result);
        }
        echo json_encode($result);exit;
    }
    

    public function checkQrLogin( $scene_id, $wx_id = 6752 ){
        
//         echo json_encode( array('ret'=> 0,'msg'=>'抱歉，请暂时使用账户密码登录，或者底下的微信登录。') );
//         exit;
        
        if( $this->currentUser['id'] ) {
            $successinfo = array(
                'ret' => 0,
                'msg' => __('Login Success'),
                'userinfo' => $this->currentUser,
            );
            $this->ajaxOutput($successinfo);
        }
        else{

            $this->loadModel('WxQrScan');
            $scanlog = $this->WxQrScan->find('first',array(
                'conditions'=> array( 'slug' => $scene_id,'wx_id' => $wx_id ),
                'order' => 'id desc',
            ));
            if(empty($scanlog)) {
                echo json_encode(array('ret'=>1)); //没有扫码登录,继续监控，直至setInterval过期被clear
            }
            else{

                $this->WxQrScan->delete($scanlog['WxQrScan']['id']); // 已识别的删除，减少发生冲突的几率
                
                if( strtotime( $scanlog['WxQrScan']['created'] ) < time() - 900 ) {
                    //返回0,终止二维码的继续检测。防止刷爆服务器
                    echo json_encode( array('ret'=> -1,'msg'=>'二维码超时，请重新生成二维码') );
                    exit;
                }
                
                $open_id = $scanlog['WxQrScan']['username'];
            
                App::uses('WeixinUtility', 'Utility');
                WeixinUtility::$appId = Configure::read('Weixin.AppId');
            
                $this->loadModel('Oauthbind');
                $oauth = $this->Oauthbind->find('first',array('conditions'=>array(
                    'source' => 'weixinPb',
                    'oauth_openid' => $open_id,
                )));
                $user_id = 0; $user_data = array();
                $client_ip = $this->request->clientIp();
                $current_time = date('Y-m-d H:i:s');

                if( empty($oauth) ) {
            
                    $userinfo = WeixinUtility::getUserInfo($open_id);
                    if( empty($userinfo['errcode']) ) {
                        if ($userinfo['gender'] == '男' || $userinfo['gender']==1) {
                            $gender = 1; //男
                        } else {
                            $gender = 0; //女
                        }

            
                        if( $userinfo['unionid'] ) {
                            $oauth = $this->Oauthbind->find('first',array('conditions'=>array(
                                'unionid' => $userinfo['unionid'],
                            )));
                            if( !empty($oauth) ) {
                                $user_id = $oauth['Oauthbind']['user_id'];
            
                                $db_user = $this->User->getUserInfo($user_id);
            
                                $user_data = $db_user['User'];
                            }
                        }

                        $new_flag = false;
            
                        if( $user_id == 0 ) {
                            $user_data = array(
                                'password' => Security::hash(random_str(12), null, true),
                                'username' => $userinfo['nickname'],
                                'image' => $userinfo['headimgurl'],
                                'sex' => $gender,
                                'role_id' => 2,
                                'last_login' => $current_time,
                                'client_ip' => $client_ip,
                                'created' => $current_time,
                                'city' => $userinfo['city'],
                                'province' => $userinfo['province'],
                                'activation_key' => md5( uniqid() ),
                                'status' => 1,
                            );
                            $this->User->save( $user_data );
                            $new_flag = true;
                            $user_data['id'] = $user_id = $this->User->getLastInsertID();
                        }
            
                        if( $user_id ) {
                            $oauth_data = array(
                                'source' => 'weixinPb',
                                'oauth_openid' => $open_id,
                                'oauth_name' => $userinfo['nickname'],
                                'unionid' => $userinfo['unionid'],
                                'user_id' => $user_id,
                            );
                            $this->Oauthbind->save($oauth_data);

                            if( !$new_flag ) {
                                $updateinfo = array(
                                    'image' => $this->User->escape_string($userinfo['headimgurl']),
                                    'nickname' => $this->User->escape_string($userinfo['nickname']),
                                    'last_login' => $this->User->escape_string($current_time),
                                    'client_ip' => $this->User->escape_string($client_ip),
                                );
                                $this->User->updateAll($updateinfo, array('id' => $user_id));
                            }

                            $this->Session->write('Auth.User', $user_data);
                            $this->Cookie->write('Auth.User', $user_data, true, 2592000);
                        }
                    }
                    else{
                        echo json_encode( array('ret'=> -1,'msg'=>'获取微信昵称信息错误。'.$userinfo['errcode']) );
                        exit;
                    }
                }
                else{
                    $user_id = $oauth['Oauthbind']['user_id'];
                    $updateinfo = array(
                        'last_login' => $this->User->escape_string($current_time),
                        'client_ip' => $this->User->escape_string($client_ip),
                    );
                    $this->User->updateAll($updateinfo, array('id' => $user_id));
            
                    $db_user = $this->User->getUserInfo($user_id);
            
                    $user_data = $db_user['User'];
            
                    $this->Session->write('Auth.User', $db_user['User']);
                    $this->Cookie->write('Auth.User',array('id' => $db_user['User']['id'],'username' => $db_user['User']['username'],'email' => $db_user['User']['email'] ), true, 2592000);
                     
                }
            
                if($user_id) {
            
                    $user = array('id' => $user_id);
                    $this->Hook->loadhook('ScoreHook');
                    $hook_results = $this->Hook->call('loginSuccess',array($user));
                    $login_score = $hook_results['ScoreHook']; unset($hook_results['ScoreHook']); // 积分数不显示在提示消息中
                    $user['login_hook_msg'] = implode('<br/>',$hook_results);
                    if($login_score){
                        $user['login_hook_msg'] .= '<BR><BR><div class="alert alert-warning alert-score text-center">'.__('Add score when first login daily').' +'.$login_score.'</div>';
                    }
            
                    if(defined('UC_APPID')) { //直接登录Ucenter的其它账号
                        App::import('Vendor', '', array('file' => 'uc_client' . DS . 'client.php'));
                        $user['session_flash'] .= uc_user_synlogin( $user['id'], $user['username'] );
                    }
            
                    $successinfo = array(
                        'ret' => 0,
                        'msg' => __('Login Success').$user['session_flash'].$user['login_hook_msg'],
                        'userinfo' => $user_data,
                        'tasks'=> array(array('dotype'=>'rscallback','callback'=>'loginSuccess')),
                    );
                    $this->ajaxOutput($successinfo);
                }
                if( empty($user_id) ) {
                    echo json_encode(array('ret'=>-1,'msg'=>'创建用户失败'));exit;
                }
            }
        }        
        exit;
    }
    
    public function keep_session(){
        
//         print_r($_COOKIE);
//         print_r($this->Cookie->read('Auth.User'));

//         print_r($_SESSION);
        //$this->Session->write('last_access',time()); // call in appcontroller::beforefilter
        
        if( $this->currentUser['id'] ) { // 登录了的，但没有cookie记录的，写入cookie信息
            if( empty($_COOKIE ['MIAOCMS'] ['Auth'] ['User']) ) {
                $this->Cookie->write('Auth.User', array(
                    'id' => $this->currentUser['id'],
                    'username' => $this->currentUser['id'],
                    'email' => $this->currentUser['id'],
                    'tt'=> time(),
                ));
            }
            
            $this->response->body(1);
            $this->response->send(); // response->send时，cookie.write才会生效
            exit;
        }
        echo 0;
        exit;
    }
    
    public function refresh_session(){
    	if($this->currentUser['id']) {
    		$this->User->recursive = 1;
    		$data = $this->User->find('first', array('conditions' => array('User.id' => $this->currentUser['id'])));
    		
    		$this->Session->write('Auth.User',$data['User']);
    		$this->Session->write('Auth.User.Role',$data['Role']);
    		echo 'user id:'.$this->currentUser['id'];
    		echo '<br>permissions:<pre>';
    		print_r($data['Role']);
    		echo '</pre>';
    	}
    	else{
    		echo 0;
    	}
    	exit;
    }
    /**
     * 
     * @param unknown $aco such as  'controllers/Uploadfiles'
     */
    public function check(){
    	$aco = $_GET['aco'];
    	if( $this->currentUser['id'] && $this->check_permition($aco) ) {
    		echo 1;exit;
    	}
    	echo 0;
    	exit;
    }

    function logout() {
        
        $this->Session->delete('Auth.User'); // 强制清空用户数据
        $this->Session->delete('User');
        $this->Cookie->destroy();
        
        $this->Session->destroy();
        $this->Session->renew();
        
        unset($this->currentUser);
//         if(defined('UC_APPID')){
//         	$hook_results = $this->Hook->call('logout');
//         	$synlogout = implode('',$hook_results); 
//         }
        
        $this->Session->setFlash(__('Logout Success'));//.$synlogout
        if($_REQUEST['state'] == 'script') {
        	echo 1;
        	exit;
        }
        else{
        	$this->redirect($this->referer());
        }
    }

    function view($username) {
        if(is_numeric($username)) {
            $user = $this->User->findById($username);
        }
        else{
            $user = $this->User->findByUsername($username);
        }
        if (!isset($user['User']['id'])) {
            $this->redirect('/');
        }

//         $this->pageTitle = $user['User']['name'];
        $this->set('user',$user);
    }

    /**
     * 
     */
    function score() {
        $this->pageTitle = __('My Scores');
    	$userinfo = $this->User->find('first',array(
    			'conditions' => array('User.id'=>$this->currentUser['id']),
    			'recursive' => -1,
    	));
    	$score = $userinfo['User']['score'];    	
    	$this->Session->write('Auth.User.score',$score); //更新session中的积分
    	$this->set('score',$score);
    }
    /**
     * 查看用户权限
     */
    function permission() {
    	
        $this->pageTitle = __('My Permissions');

    	if(!empty($this->currentUser['id'])) {

    		$userinfo = $this->User->getUserById($this->currentUser['id']);

	    	$this->Session->write('Auth.User',$userinfo['User']);
	    	$this->Session->write('Auth.User.Role',$userinfo['Role']); //更新session中的权限
	    	$this->set('userinfo',$userinfo);
    	}
    	else{
    		$this->set('userinfo',array('Role'=>array()));
    	}
    }
}

?>